import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/FileUpLoadBean.dart';
import 'package:flutter_ahj_app/base/bean/flutter_AMapLocation_map.dart';
import 'package:flutter_ahj_app/base/utils/HttpUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import 'package:flutter_ahj_app/base/utils/image_picked.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/SelectPicUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import '../../../base/utils/video_player_page.dart';
import 'package:permission_handler/permission_handler.dart';

class YhzlzgView extends BaseStatefulWidget {
  final Map zgMap;
  YhzlzgView({this.zgMap});

  @override
  State<StatefulWidget> initState() {
    return YhzlzgViewState();
  }
}

class YhzlzgViewState extends BaseState<YhpcViewModel, YhzlzgView> {
  TextEditingController _zrrCtr = TextEditingController(); // 责任人
  TextEditingController _zgwcsjCtr = TextEditingController(); // 整改完成时间
  TextEditingController _yhzrbmCtr = TextEditingController(); // 隐患责任部门
  TextEditingController _zgcsCtr = TextEditingController(); // 整改措施
  TextEditingController _zgqkCtr = TextEditingController(); // 整改情况
  TextEditingController _zgzjCtr = TextEditingController(); // 整改资金
  TextEditingController _ysrCtr = TextEditingController(); // 验收人

  AMapLocation location;
  List<String> _imageUrls = [];
  String _ysrId = '';
  String _selOrgCode = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _zgwcsjCtr.text = DateUtil.getDateStrByDateTime(
            DateTime.parse(DateTime.now().toString()),
            format: DateFormat.YEAR_MONTH_DAY_HOUR_MINUTE) +
        ':00';
    if (!StringUtils.isEmpty(widget.zgMap['id'].toString())) {
      _initData();
    }
  }

  _initData() {
    viewModel.yhzlListDetail(widget.zgMap['id'].toString());
    viewModel.yhzlListDetailStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          var _dataM = event['data'];

          _yhzrbmCtr.text = StringUtils.getStr(_dataM['riskPointOrgCodeName']);
          _zrrCtr.text =
              StringUtils.getStr(_dataM['rectifyResponsiblePersonName']);
          _selOrgCode = StringUtils.getStr(
              _dataM['rectifyResponsibleOrgCode'].toString());
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '整改',
      ).create(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                  color: SQColor.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    _commField(
                        isMust: true,
                        controller: _zgwcsjCtr,
                        title: '整改完成时间',
                        hintText: '请选择完成时间',
                        isReadOnly: true,
                        suffixIcon: Image.asset(
                          "img/field_date.png",
                          width: Dimens.dimens15,
                          height: Dimens.dimens15,
                        ),
                        onTap: () {
                          _datePicker(true);
                        }),
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                JText(
                                  '* ',
                                  color: SQColor.red,
                                ),
                                Container(
                                  child: JText('整改后的隐患视图'),
                                ),
                              ],
                            ),
                          ),
                          buildImagePicked(context, true),
                        ],
                      ),
                    ),
                    _commField(
                      isMust: true,
                      controller: _zgcsCtr,
                      title: '隐患整改措施',
                      hintText: '请输入隐患整改措施',
                      maxLength: 500,
                    ),
                    _commField(
                      isMust: true,
                      controller: _zgqkCtr,
                      title: '隐患整改情况',
                      hintText: '请输入隐患整改情况',
                      maxLength: 500,
                    ),
                    _commField(
                        title: '隐患责任部门',
                        hintText: '',
                        isEdit: true,
                        isReadOnly: true,
                        controller: _yhzrbmCtr),
                    _commField(
                      title: '隐患整改责任人',
                      hintText: '',
                      isEdit: true,
                      controller: _zrrCtr,
                      isReadOnly: true,
                    ),
                    _commField(
                      controller: _zgzjCtr,
                      title: '隐患整改资金（元）',
                      hintText: '请输入隐患整改资金（元）',
                      inputFormatters: [
                        LengthLimitingTextInputFormatter(8),
                        FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                      ],
                    ),
                    _commField(
                        isMust: true,
                        title: '验收人',
                        hintText: '请选择验收人',
                        controller: _ysrCtr,
                        isReadOnly: true,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, '/ChoosePersonDan',
                                  arguments: '')
                              .then((value) {
                            if (value != null) {
                              Map map = value;
                              _ysrId = map['openId'];
                              _ysrCtr.text = map['name'];
                            }
                          });
                        }),
                    Container(
                      height: 20,
                    ),
                  ],
                ),
              ),
            ),
          ),
          _bottomView()
        ],
      ),
    );
  }

  int _maxCount = 6;
  Widget buildImagePicked(BuildContext context, bool isBefore) {
    return new Container(
        padding: const EdgeInsets.all(10.0),
        child: GridView.builder(
            padding: EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4, //每行三列
                childAspectRatio: 1.0 //显示区域宽高相等
                ),
            itemCount: _imageUrls.length == 0
                ? 1
                : (_imageUrls.length == _maxCount
                    ? _imageUrls.length
                    : _imageUrls.length + 1),
            itemBuilder: (context, index) {
              return _item(index);
            }));
  }

  _item(int index) {
    List imgs = _imageUrls;
    return new GestureDetector(
      onTap: () {
        if (index != imgs.length) {
          if (imgs[index].contains("mp4")) {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => VideoPlayerPage(
                          videoPath: imgs[index],
                          videoSource: "2",
                        )));
          } else {
            List<String> filePath = [];
            int position = 0;
            for (int i = 0; i < imgs.length; i++) {
              if (!imgs[i].contains(".mp4")) {
                filePath.add(imgs[i]);
              }
            }
            for (int i = 0; i < filePath.length; i++) {
              if (filePath[i] == imgs[index]) {
                position = i;
              }
            }
            Navigator.pushNamed(context, "/ShowImage",
                arguments: {'position': position, 'filePath': filePath});
          }
        } else {
          _pickImage();
        }
      },
      child: index != imgs.length
          ? Container(
              margin: EdgeInsets.only(right: 5, bottom: 5),
              child: ImagePicked(
                key: UniqueKey(),
                imageUrl: imgs[index],
                closeState: "0",
                index: index,
                boxFit: BoxFit.cover,
                valueChanged: (index) {
                  setState(() {
                    imgs.removeAt(index);
                  });
                },
              ),
            )
          : new Container(
              color: Theme.of(context).dividerColor,
              width: (MediaQuery.of(context).size.width - 32.0 - 8.0) / 4,
              height: (MediaQuery.of(context).size.width - 32.0 - 8.0) / 4,
              child: new Icon(
                Icons.add,
                size: 20.0,
                color: Colors.grey,
              ),
            ),
    );
  }

  bool showing = false;
  //多图选择器
  _pickImage() async {
    showing = true;
    showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('*选择附件(隐患视图)'),
          children: <Widget>[
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '照相',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("0");
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '从相册选择',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("1");
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '视频录制',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("2");
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
          ],
        );
      },
    );
  }

  void onSelectPicClick(String type) async {
    List imgs = _imageUrls;
    List result;
    Map<String, String> map = {
      "count": (_maxCount - imgs.length).toString(),
      "adress": location == null ? "暂无获取定位信息" : location.locationDescribe
    };
    if ("0" == type) {
      //照相
      if (location == null) {
        String resultStr =
            await PerUtils.checkPermission(context, [Permission.location]);
        if (resultStr == '1') {
          location = await FlutterAMapLocation.getCurrentLocation();
          if (location == null) {
            ToastUtils.showToast("获取位置信息失败，暂不能拍照");
          } else {
            map["adress"] = location.locationDescribe;
            String resultStr =
                await PerUtils.checkPermission(context, [Permission.camera]);
            if (resultStr == '1') {
              result = await SelectPicUtils.getTakePic(map);
            }
          }
        } else {
          ToastUtils.showToast("获取位置信息失败，暂不能拍照");
        }
      } else {
        String resultStr =
            await PerUtils.checkPermission(context, [Permission.camera]);
        if (resultStr == '1') {
          result = await SelectPicUtils.getTakePic(map);
        }
      }
      //照相
    } else if ("1" == type) {
      //选择图片
      result = await SelectPicUtils.getSelectPic(map);
    } else if ("2" == type) {
      var microphoneStatus = await Permission.microphone.request();
      var cameraStatus = await Permission.camera.request();
      var storageStatus = await Permission.storage.request();

// String resultStr = await PerUtils.checkPermission(
//     context, [Permission.speech, Permission.camera, Permission.microphone]);

      if (cameraStatus == PermissionStatus.granted && microphoneStatus == PermissionStatus.granted && storageStatus == PermissionStatus.granted) {
        // 权限被授予，可以拍摄视频
        result = await SelectPicUtils.getSelectVideo(map);
      }else {
        ToastUtils.showToast("请先获取相机/录音等权限");
        return;
      }

    }
    setState(() {
      result.forEach((f) {
        imgs.add(f);
      });
    });
  }

  _bottomView() {
    return Row(
      children: [
        Expanded(
          child: InkWell(
            onTap: () {
              _done();
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15),
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: SQColor.theme_color,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: JText('确定', color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }

  _datePicker(bool isStart) {
    String jbTime = '';
    showDatePicker(
      context: context,
      initialDate: new DateTime.now(), // 加 30 天
      firstDate:
          new DateTime.now().subtract(new Duration(days: 3650)), // 减 30 天
      lastDate: new DateTime.now().add(new Duration(days: 3650)),
    ).then((DateTime val) {
      showTimePicker(
        context: context,
        initialTime: new TimeOfDay.now(),
      ).then((val1) {
        if (val1 == null) {
          return;
        }
        setState(() {
          jbTime = DateUtil.getDateStrByDateTime(DateTime.parse(val.toString()),
              format: DateFormat.YEAR_MONTH_DAY);
          String hour1 = val1.hour < 10
              ? "0" + val1.hour.toString()
              : val1.hour.toString();
          String hour2 = val1.minute < 10
              ? "0" + val1.minute.toString()
              : val1.minute.toString();

          jbTime = jbTime +
              " " +
              hour1 +
              ":" +
              hour2 +
              ":" +
              "00"; // 2018-07-12 00:00:00.000018-07-12 00:00:00.000
          if (isStart) {
            _zgwcsjCtr.text = jbTime;
          } else {
            _zgwcsjCtr.text = jbTime;
          }
        });
      }).catchError((err) {
        print(err);
      });
    }).catchError((err) {
      print(err);
    });
  }

  // 提交保存
  _done() {
    if (_zgwcsjCtr.text.isEmpty) {
      ToastUtils.showToast('请填写整改完成时间');
      return;
    }
    if (_imageUrls.length == 0) {
      ToastUtils.showToast('请选择整改后隐患视图');
      return;
    }
    if (_zgcsCtr.text.isEmpty) {
      ToastUtils.showToast('请填写隐患整改措施');
      return;
    }
    if (_zgqkCtr.text.isEmpty) {
      ToastUtils.showToast('请填写隐患整改情况');
      return;
    }
    if (StringUtils.isEmpty(_ysrId)) {
      ToastUtils.showToast('请填写验收人');
      return;
    }
    _upLoadImage();
  }

  _upLoadImage() {
    List<String> _uploadimageUrls = [];
    for (int i = 0; i < _imageUrls.length; i++) {
      _uploadimageUrls.add(_imageUrls[i]);
    }

    HttpUtils.httpUpLoadPost(
        HttpBaseConst.serverUrl + HttpBaseConst.UPLOAD, _uploadimageUrls,
        (data) {
      setState(() {
        FileUpLoadBean fileUpLoadBean =
            FileUpLoadBean.fromJson(json.decode(data));
        List filepath = [];
        for (int i = 0; i < fileUpLoadBean.data.length; i++) {
          Map map = {
            'fileName': fileUpLoadBean.data[i].fileName,
            'url': fileUpLoadBean.data[i].urlPath,
          };
          filepath.add(map);
        }
        _submit(filepath);
      });
    }, context: context);
  }

  _submit(
    var hazardRectifyAfterFileList,
  ) {
    var map = {
      'hazardId': StringUtils.getStr(widget.zgMap['id'].toString()),
      'rectifyCompleteTime': _zgwcsjCtr.text,
      'hazardRectifyAfterFileList': hazardRectifyAfterFileList,
      'rectifyMeasure': _zgcsCtr.text,
      'rectifyDescription': _zgqkCtr.text,
      'rectifyResponsibleOrgCode': _selOrgCode,
      'rectifyMoney': _zgzjCtr.text.isEmpty ? null : _zgzjCtr.text,
      'acceptorOpenId': _ysrId
    };
    ToastUtils.showLoading();
    viewModel.yhzg(map);
    viewModel.yhzgDataStream().listen((event) {
      ToastUtils.dissLoading();
      if (event['code'] == '0') {
        ToastUtils.showToast('提交成功');
        Navigator.of(context)
          ..pop()
          ..pop();
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      ToastUtils.dissLoading();
      print(e);
    });
  }

  _commField(
      {bool isMust = false,
      String hintText = '',
      Widget suffixIcon,
      String title = '',
      bool isReadOnly = false,
      int maxLength,
      bool isEdit = false, //是否可编辑
      var onTap,
      var controller,
      var inputFormatters}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            child: Row(
              children: [
                isMust
                    ? JText(
                        '* ',
                        color: SQColor.red,
                      )
                    : Container(),
                Container(
                  child: JText(title),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(
                left: 10,
                right: maxLength == null ? 0 : 10,
                bottom: maxLength == null ? 0 : 10),
            child: TextField(
              inputFormatters: inputFormatters,
              controller: controller,
              onTap: onTap,
              maxLength: maxLength,
              readOnly: isReadOnly,
              style: TextStyle(fontSize: Dimens.textSize28),
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  suffixIcon: suffixIcon),
            ),
            decoration: BoxDecoration(
              color: isEdit ? SQColor.lineE7E7E7 : SQColor.white,
              border: Border.all(
                width: 1,
                color: SQColor.lineE7E7E7,
              ),
              borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens4)),
            ),
          ),
        ],
      ),
    );
  }
}
